/*
*  Copyright 2019-2023 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.system.rest;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import me.zhengjie.annotation.Log;
import me.zhengjie.modules.system.domain.User;
import me.zhengjie.modules.system.domain.Userexercisesetlog;
import me.zhengjie.modules.system.domain.Userquestionlog;
import me.zhengjie.modules.system.domain.vo.UserexercisesetlogQueryCriteria;
import me.zhengjie.modules.system.mapper.UserMapper;
import me.zhengjie.modules.system.service.UserService;
import me.zhengjie.modules.system.service.UserexercisesetlogService;
import me.zhengjie.modules.system.service.UserquestionlogService;
import me.zhengjie.utils.PageResult;
import org.apache.ibatis.annotations.Param;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
* @author shitou
* @date 2024-05-29
**/
@RestController
@RequiredArgsConstructor
@Api(tags = "习题集答题记录管理")
@RequestMapping("/api/userexercisesetlog")
public class UserexercisesetlogController {

    private final UserexercisesetlogService userexercisesetlogService;

    private final UserService userService;

    private final UserquestionlogService userquestionlogService;

    @Log("导出数据")
    @ApiOperation("导出数据")
    @GetMapping(value = "/download")
    @PreAuthorize("@el.check('userexercisesetlog:list')")
    public void exportUserexercisesetlog(HttpServletResponse response, UserexercisesetlogQueryCriteria criteria) throws IOException {
        userexercisesetlogService.download(userexercisesetlogService.queryAll(criteria), response);
    }

    @GetMapping
    @Log("查询习题集答题记录")
    @ApiOperation("查询习题集答题记录")
    @PreAuthorize("@el.check('userexercisesetlog:list')")
    public ResponseEntity<PageResult<Userexercisesetlog>> queryUserexercisesetlog(UserexercisesetlogQueryCriteria criteria, Page<Object> page){
        return new ResponseEntity<>(userexercisesetlogService.queryAll(criteria,page),HttpStatus.OK);
    }



    @GetMapping("/queryMsg")
    @Log("查询习题集答题记录")
    @ApiOperation("查询习题集答题记录")
//    @PreAuthorize("@el.check('userexercisesetlog:list')")
    public ResponseEntity<Userexercisesetlog> queryMsg(@Param("resources") Userexercisesetlog resources){

        Userexercisesetlog userexercisesetlog = new Userexercisesetlog();
                QueryWrapper queryWrapper = new QueryWrapper<>();

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String currentUserName = authentication.getName();
        User currentUser = userService.getOne(new QueryWrapper<User>().eq("username", currentUserName));
        if(resources.getId()!=null){
            queryWrapper.eq("id",resources.getId());

            userexercisesetlog = userexercisesetlogService.getOne(queryWrapper);
        } else {
            if(resources.getTeachchapterid()!=null){
                queryWrapper.eq("teachChapterId",resources.getTeachchapterid());
            }
            if(resources.getTeachsubsectionid()!=null){

                queryWrapper.eq("teachSubsectionId",resources.getTeachsubsectionid());
            }
            queryWrapper.eq("subsectionExerciseSetId",resources.getSubsectionexercisesetid());


            if(resources.getCourseid()!=null){

                queryWrapper.eq("courseId",resources.getCourseid());
            }
            if(resources.getExercisesetid()!=null){

                queryWrapper.eq("exerciseSetId",resources.getExercisesetid());

            }
            if(resources.getType()!=null){

                queryWrapper.eq("type",resources.getType());
            }
            if(currentUser.getId()!=null){
                queryWrapper.eq("userId",currentUser.getId());
            }
//            List<Userexercisesetlog> userexercisesetlogs = userexercisesetlogService.list(queryWrapper);

            userexercisesetlog = userexercisesetlogService.getOne(queryWrapper);
        }

        return new ResponseEntity<>(userexercisesetlog,HttpStatus.OK);
    }

//
    @GetMapping("/getExercisesetResult")
    @Log("教师获取学生试卷结果")
    @ApiOperation("教师获取学生试卷结果")
    public ResponseEntity<Userexercisesetlog> getExercisesetResult(@Param("resources") Userexercisesetlog resources){


        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String currentUserName = authentication.getName();
        User currentUser = userService.getOne(new QueryWrapper<User>().eq("username", currentUserName));
        Userexercisesetlog userexercisesetlog = new Userexercisesetlog();
        QueryWrapper queryWrapper = new QueryWrapper<>();

        if(resources.getTeachchapterid()!=null){
            queryWrapper.eq("teachChapterId",resources.getTeachchapterid());
        }
        if(resources.getTeachsubsectionid()!=null){

            queryWrapper.eq("teachSubsectionId",resources.getTeachsubsectionid());
        }
        queryWrapper.eq("subsectionExerciseSetId",resources.getSubsectionexercisesetid());


        if(resources.getCourseid()!=null){

            queryWrapper.eq("courseId",resources.getCourseid());
        }
        if(resources.getExercisesetid()!=null){

            queryWrapper.eq("exerciseSetId",resources.getExercisesetid());

        }
        if(resources.getType()!=null){

            queryWrapper.eq("type",resources.getType());
        }
        if(resources.getUserid()!=null){
            queryWrapper.eq("userId",currentUser.getId());
        }
        userexercisesetlog = userexercisesetlogService.getOne(queryWrapper);
        if(userexercisesetlog!=null){
            QueryWrapper userexercisesetlogQueryWrapper = new QueryWrapper();
            userexercisesetlogQueryWrapper.eq("userExerciseSetLogId",userexercisesetlog.getId());
            userexercisesetlogQueryWrapper.eq("userId",currentUser.getId());
            List<Userquestionlog> userquestionlogs= userquestionlogService.list(userexercisesetlogQueryWrapper);
            System.out.println("userquestionlogs:"+userquestionlogs);
            for(Userquestionlog userquestionlog:userquestionlogs){
                if(userquestionlog.getQuestiontype() == 0 && userexercisesetlog.getSingleNum()!=null){

                    userexercisesetlog.setSingleNum(userexercisesetlog.getSingleNum()+1);
                    userexercisesetlog.setSingleScore(userexercisesetlog.getSingleScore()+Integer.parseInt(userquestionlog.getScore()));
                } else if(userquestionlog.getQuestiontype() == 1 && userexercisesetlog.getMultipleNum()!=null){

                    userexercisesetlog.setMultipleNum(userexercisesetlog.getMultipleNum()+1);
                    userexercisesetlog.setMultipleScore(userexercisesetlog.getMultipleScore()+Integer.parseInt(userquestionlog.getScore()));
                } else if(userquestionlog.getQuestiontype() == 2 && userexercisesetlog.getJudgeNum()!=null){

                    userexercisesetlog.setJudgeNum(userexercisesetlog.getJudgeNum()+1);
                    userexercisesetlog.setJudgeScore(userexercisesetlog.getJudgeScore()+Integer.parseInt(userquestionlog.getScore()));
                } else if(userquestionlog.getQuestiontype() == 3 && userexercisesetlog.getCompletionNum()!=null){

                    userexercisesetlog.setCompletionNum(userexercisesetlog.getCompletionNum()+1);
                    userexercisesetlog.setCompletionScore(userexercisesetlog.getCompletionScore()+Integer.parseInt(userquestionlog.getScore()));
                } else if(userquestionlog.getQuestiontype() == 4 && userexercisesetlog.getShortNum()!=null){

                    userexercisesetlog.setShortNum(userexercisesetlog.getShortNum()+1);
                    userexercisesetlog.setShortScore(userexercisesetlog.getShortScore()+Integer.parseInt(userquestionlog.getScore()));
                }
                if(userquestionlog.getScore()!=null){
                    if(userexercisesetlog.getAllScore() == null){
                        userexercisesetlog.setAllScore(0);
                    }
                    userexercisesetlog.setAllScore(userexercisesetlog.getAllScore()+Integer.parseInt(userquestionlog.getScore()));

                }
            }
        }

        return new ResponseEntity<>(userexercisesetlog,HttpStatus.OK);
    }

    @GetMapping("/getResult")
    @Log("学生获取试卷结果")
    @ApiOperation("学生获取试卷结果")
    public ResponseEntity<Userexercisesetlog> getResult(@Param("resources") Userexercisesetlog resources){
        Userexercisesetlog userexercisesetlog = new Userexercisesetlog();
        QueryWrapper queryWrapper = new QueryWrapper<>();

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String currentUserName = authentication.getName();
        User currentUser = userService.getOne(new QueryWrapper<User>().eq("username", currentUserName));
        if(resources.getTeachchapterid()!=null){
            queryWrapper.eq("teachChapterId",resources.getTeachchapterid());
        }
        if(resources.getTeachsubsectionid()!=null){

            queryWrapper.eq("teachSubsectionId",resources.getTeachsubsectionid());
        }
        queryWrapper.eq("subsectionExerciseSetId",resources.getSubsectionexercisesetid());


        if(resources.getCourseid()!=null){

            queryWrapper.eq("courseId",resources.getCourseid());
        }
        if(resources.getExercisesetid()!=null){

            queryWrapper.eq("exerciseSetId",resources.getExercisesetid());

        }
        if(resources.getType()!=null){

            queryWrapper.eq("type",resources.getType());
        }
        if(currentUser.getId()!=null){
            queryWrapper.eq("userId",resources.getUserid());
        }
        userexercisesetlog = userexercisesetlogService.getOne(queryWrapper);
        if(userexercisesetlog!=null){
            QueryWrapper userexercisesetlogQueryWrapper = new QueryWrapper();
            userexercisesetlogQueryWrapper.eq("userExerciseSetLogId",userexercisesetlog.getId());
            userexercisesetlogQueryWrapper.eq("userId",resources.getUserid());
            List<Userquestionlog> userquestionlogs= userquestionlogService.list(userexercisesetlogQueryWrapper);
            for(Userquestionlog userquestionlog:userquestionlogs){
                if(userquestionlog.getQuestiontype() == 0){

                    userexercisesetlog.setSingleNum(userexercisesetlog.getSingleNum()+1);
                    userexercisesetlog.setSingleScore(userexercisesetlog.getSingleScore()+Integer.parseInt(userquestionlog.getScore()));
                } else if(userquestionlog.getQuestiontype() == 1){

                    userexercisesetlog.setMultipleNum(userexercisesetlog.getMultipleNum()+1);
                    userexercisesetlog.setMultipleScore(userexercisesetlog.getMultipleScore()+Integer.parseInt(userquestionlog.getScore()));
                } else if(userquestionlog.getQuestiontype() == 2){

                    userexercisesetlog.setJudgeNum(userexercisesetlog.getJudgeNum()+1);
                    userexercisesetlog.setJudgeScore(userexercisesetlog.getJudgeScore()+Integer.parseInt(userquestionlog.getScore()));
                } else if(userquestionlog.getQuestiontype() == 3){

                    userexercisesetlog.setCompletionNum(userexercisesetlog.getCompletionNum()+1);
                    userexercisesetlog.setCompletionScore(userexercisesetlog.getCompletionScore()+Integer.parseInt(userquestionlog.getScore()));
                } else if(userquestionlog.getQuestiontype() == 4){

                    userexercisesetlog.setShortNum(userexercisesetlog.getShortNum()+1);
                    userexercisesetlog.setShortScore(userexercisesetlog.getShortScore()+Integer.parseInt(userquestionlog.getScore()));
                }
                userexercisesetlog.setAllScore(userexercisesetlog.getAllScore()+Integer.parseInt(userquestionlog.getScore()));
            }
        }

        return new ResponseEntity<>(userexercisesetlog,HttpStatus.OK);
    }

    @PostMapping
    @Log("新增习题集答题记录")
    @ApiOperation("新增习题集答题记录")
//    @PreAuthorize("@el.check('userexercisesetlog:add')")
    public ResponseEntity<Object> createUserexercisesetlog(@Validated @RequestBody Userexercisesetlog resources){


        userexercisesetlogService.create(resources);
        return new ResponseEntity<>(HttpStatus.CREATED);
    }

    @PutMapping
    @Log("修改习题集答题记录")
    @ApiOperation("修改习题集答题记录")
//    @PreAuthorize("@el.check('userexercisesetlog:edit')")
    public ResponseEntity<Object> updateUserexercisesetlog(@Validated @RequestBody Userexercisesetlog resources){

        userexercisesetlogService.update(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @DeleteMapping
    @Log("删除习题集答题记录")
    @ApiOperation("删除习题集答题记录")
    @PreAuthorize("@el.check('userexercisesetlog:del')")
    public ResponseEntity<Object> deleteUserexercisesetlog(@RequestBody List<Integer> ids) {
        userexercisesetlogService.deleteAll(ids);
        return new ResponseEntity<>(HttpStatus.OK);
    }
}